'use strict';

const moment = require('moment');


exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  const { userId } = await ctx.model.WechatAccount.findByPk(openId);
  const { id, status, storeId } = query;
  if (id) where.id = id;
  if (userId) where.userId = userId;
  if (storeId) where.storeId = storeId;
  switch (status) {
    case 'useable':
      where.usedAt = null;
      where.expiredDate = {
        [ctx.model.Op.gte]: moment().format('YYYYMMDD'),
      };
      break;
    case 'used':
      where.usedAt = {
        [ctx.model.Op.not]: null,
      };
      break;
    case 'expired':
      where.usedAt = null;
      where.expiredDate = {
        [ctx.model.Op.lte]: moment().format('YYYYMMDD'),
      };
      break;
    default:

  }
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Coupon.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.show = async ctx => {
  const options = { raw: true };
  const coupon = await ctx.model.Coupon.findByPk(ctx.params.id, options);
  if (coupon) {
    ctx.body = coupon;
  } else {
    ctx.status = 404;
  }
};
